package us.mooresr.webtroopmanager.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LoginViewImpl extends Composite implements LoginView {
	private Presenter presenter;
	
	private static LoginViewUiBinder uiBinder = GWT.create(LoginViewUiBinder.class);
	
	interface LoginViewUiBinder extends UiBinder<Widget, LoginViewImpl> {
		
	}
	
	@UiField
	TextBox userNameTextBox;
	
	@UiField
	PasswordTextBox passwordTextBox;
	
	@UiField
	Button loginButton;
	
	@UiHandler("loginButton")
	void onLoginButton(ClickEvent e) {
		presenter.doLogin(userNameTextBox.getText(), passwordTextBox.getText());
	}
	
	@UiHandler("userNameTextBox")
	void onUserNameKey(KeyDownEvent e) {
		if (e.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			passwordTextBox.setFocus(true);
		}	
	}
	
	@UiHandler("passwordTextBox")
	void onPasswordKey(KeyDownEvent e) {
		if (e.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
			presenter.doLogin(userNameTextBox.getText(), passwordTextBox.getText());
		}	
	}

	
	public LoginViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
	}
	


	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
		
	}

	@Override
	public void clear() {
		userNameTextBox.setValue("");
		passwordTextBox.setValue("");
		Scheduler defaultScheduler = Scheduler.get();
		defaultScheduler.scheduleDeferred(new Scheduler.ScheduledCommand() {
			public void execute() {
				userNameTextBox.setFocus(true);
			}
		});
		
	}

}
